package com.lnt.java.thread.safe;

/**
 * <p>利用同步代码块的方法来实现线程安全</p>
 */
public class TicketSafeSynchronizedBlaakTest implements Runnable {

    private int ticket = 100;

    Object lock = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (ticket >0) {
                    // 模拟出票业务执行
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 只要有票就一直卖出
                    System.out.println(Thread.currentThread().getName() + " 卖了第" + ticket--);
                }
            }
        }
    }
}
